import csv

data = [('Bob', '14'), ('Tom', '23'), ('Jerry', '18'), ('码云', '10')]
'''r w a r+'''

# 添加newline可以避免一行之后的空格,这样需要在python3环境下运行
with open('example.csv', 'a', encoding='utf-8-sig', newline='') as f_csv:
    writer = csv.writer(f_csv)
    # for row in data:
    #     writer.writerow(row)
    # 写入一行用writerow 每次写完一行之后，会自动换行
    writer.writerow(['name', 'age'])
    # 多行用writerows
    writer.writerows(data)
with open('example.csv', 'r') as f_csv:
    # csv包提供了reader方法， 它接受一个文件对象， 返回一个csv reader对象,是迭代类型
    reader = csv.reader(f_csv)
    # 读取一行，下面的reader中已经没有该行了
    # 要注意的是，reader只能被遍历一次。由于reader是可迭代对象，可以使用next方法一次获取一行。
    head_row = next(reader)
    for row in reader:
        # 行号从2开始
        # 每行数据会有一个属性：line_num表示行数
        print(reader.line_num, row)
        print(row[0])
        print(row[0], row[1])

with open('example.csv', 'r') as f_csv:
    dict_reader = csv.DictReader(f_csv)
    head_row = next(dict_reader)
    for row in dict_reader:
        print(row)

import os
def WriteToCsv():
  '''写CSV文件'''
  titls = ['序号', '链接', '备注']
  data = [
    ['1', 'http://www.xiaoheiseo.com/', '小黑'],
    ['2', 'http://www.baidu.com/', '百度'],
    ['3', 'http://www.jd.com/', '京东']
  ]
  csvfile = os.path.join(os.getcwd(),'csvtest.csv')
  with open(csvfile, 'w') as f:
    writer = csv.writer(f)
    # 标题
    writer.writerow(titls)
    # 内容
    writer.writerows(data)

def ReadCSV():
  '''读取CSV文件'''
  filename = os.path.join(os.getcwd(), 'csvtest.csv')
  if os.path.exists(filename):
    with open(filename, 'r') as f:
      reader = csv.reader(f)
      for item in reader:
        print(item)

# WriteToCsv()
# ReadCSV()